import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { PageModalService } from 'src/app/shared/service/page-modal-service';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';
import { IonRange, ModalController } from '@ionic/angular';
import { Network } from '@ionic-native/network/ngx';
@Component({
  selector: 'app-video-img-popup',
  templateUrl: './video-img-popup.component.html',
  styleUrls: ['./video-img-popup.component.scss'],
})
export class VideoImgPopupComponent implements OnInit {
  @Input() tagData: any;
  @Input() style: any;
  @ViewChild('range') range: IonRange;
  titleTips: any;
  showVidoe = true;
  slideOpts: any;
  videoPlayIcon: any;
  video: any;
  test = true;
  index = 0;
  seekbar: any;
  hiddenLoading = false;
  percent = 0; // 当前进度
  currentTime = "0:00"; // 当前时间
  totalTime = "0:00"; // 总时间
  showDaggerProgress = false; // 拉动进度
  hiddedMinPlayProgress = true; // 小进度
  videosData: any = [];
  playIconCss = `width:5rem;height: 5rem;background: url('../../../assets/fw/video_icon_suspend@3x.png') no-repeat;background-size:5rem;`;

  constructor(
    public network: Network,
    private appGlobalService: AppGlobalService,
    private pageModalService: PageModalService,
    public modalController: ModalController,
  ) { }

  ngOnInit() {
    if (this.style && this.style === 'commentsListTag') {
      if (this.tagData.videoUrl) { // 可能是多个
        this.videosData = this.tagData.videoUrl;
      }
    } else {
      if (this.tagData.videoUrl || this.tagData.imgUrl) {
        if (this.tagData.imgUrl === undefined) {
          this.videosData = this.tagData.videoUrl;
        } else if (this.tagData.videoUrl === undefined) {
          this.videosData = this.tagData.imgUrl;
        } else {
          this.videosData = this.tagData.videoUrl.concat(this.tagData.imgUrl);   // 视频和图片
        }
      }
    }
    this.getCurrentTitle();

    setTimeout(() => {
      const ele = document.querySelectorAll('video[ishivideo="true"]');
      this.video = ele;
      // 如果没有播放 就开始播放吧
      if (this.video && this.video[this.index] && this.video[this.index].paused) {
          const playBtn = document.getElementById('id-playBtn' + this.index);
          if (playBtn) {
            playBtn.click();
          }
      }
      document.getElementById('footer-drag-progress').addEventListener("touchstart", () => {
        this.showDaggerProgress = true;
      });
      document.getElementById('footer-drag-progress').addEventListener("touchend", () => {
        setTimeout(() => {
          this.showDaggerProgress = false;
        }, 800);
        const currentValue = Number(this.range.value) ;
        this.video[this.index].currentTime = (this.video[this.index].duration * (currentValue / 100)).toFixed(2);
      });

      // 媒体数据加载完成
      this.video[this.index].addEventListener("loadedmetadata", () => {
        this.hiddedMinPlayProgress = false;
        // 如果没有播放 就开始播放吧
        if (this.video && this.video[this.index] && this.video[this.index].paused) {
          const playBtn = document.getElementById('id-playBtn' + this.index);
          if (playBtn) {
            playBtn.click();
          }
          this.hiddenLoading = true;
        } else if (this.video && this.video[this.index] && !this.video[this.index].paused) {
          this.hiddenLoading = true;
        }
      });
      // video事件更新
      if (this.video && this.video[this.index] !== undefined ) {
        this.video[this.index].addEventListener("timeupdate", () => {
          if (this.index >= this.video.length) {
            return;
          } else {
            this.hiddenLoading = true;
            this.percent  = (100 / this.video[this.index].duration) * this.video[this.index].currentTime;
            const playProgressInner = document.getElementById('play-progress-inner');
            if (playProgressInner) {
              playProgressInner.setAttribute( 'style', 'width:' + this.percent + '%');
            }
            if (!this.showDaggerProgress && this.range !== undefined) {
              this.range.value = this.percent;
              // 更新当前时间
              this.currentTime = this.getTimeBySecond(this.video[this.index].currentTime);
              this.totalTime = this.getTimeBySecond(this.video[this.index].duration);
            }
          }
        });
      }

    }, 200);

    setTimeout(() => {
      this.hiddedMinPlayProgress = false;
      // 如果没有播放 就开始播放吧
      if (this.video && this.video[this.index] && this.video[this.index].paused) {
        const playBtn = document.getElementById('id-playBtn' + this.index);
        if (playBtn) {
          playBtn.click();
        }
        this.hiddenLoading = true;
      } else if (this.video && this.video[this.index] && !this.video[this.index].paused) {
        this.hiddenLoading = true;
      } else {
        setTimeout(() => {
          this.hiddenLoading = true;
        }, 1000);
      }
      this.getNetType();
      if (this.video[this.index] && this.video[this.index].duration) {
        this.totalTime = this.getTimeBySecond(this.video[this.index].duration);
      }

    }, 1500);

  }

  getNetType() {
    try {
      let wifi = true;
      const ua = window.navigator.userAgent;
      // 如果是微信
      if (/MicroMessenger/.test(ua)) {
          if (ua.indexOf('WIFI') >= 0) {
              return true;
          } else {
              wifi = false;
          }
      } else if (this.network.type !== 'none') {
          if (this.network.type !== 'wifi' &&
          this.network.type !== 'ethernet' &&
          this.network.type !== 'unknown' &&
          this.network.type !== null) {
              wifi = false;
          }
      }
      if (this.network.type === 'none') {
          this.appGlobalService.showToast('当前网络状异常,请检查网络设置~', 1500, 'middle');
      } else {
        if (!wifi) {
          this.appGlobalService.showToast('当前网络状态不是wifi，请注意流量消耗~', 1500, 'middle');
        }
      }

      } catch (e) {
        return false;
      }
  }
  // 拖动时间进度
  rangeChange(event) {
    if (this.showDaggerProgress) {
      const currentValue = event.detail.value;
      this.currentTime = this.getTimeBySecond((this.video[this.index].duration * (currentValue / 100)).toFixed(2));
      this.video[this.index].currentTime = (this.video[this.index].duration * (currentValue / 100)).toFixed(2);

    }
  }
  rangeOn(event) {
    this.showDaggerProgress = true;
  }
  rangeOff(event) {

  }
  getCurrentTitle() {
    this.titleTips = Number(this.index + 1) + " / " + this.videosData.length ;
    return this.titleTips;
  }

  queryById(selector) {
    return document.getElementById(selector);
  }
  getClass(elem) {
    return elem.getAttribute && elem.getAttribute("class") || "";
  }
  addClass(ele, value) {
    if (value) {
      let curValue = this.getClass(ele);
      if (curValue.indexOf(value) === -1) {
        curValue = curValue + " " + value;
      }
      ele.setAttribute("class", curValue.trim());
    }
  }
  /**
   * 删除class
   */
  removeClass(ele, value) {
    if (value) {
      let curValue = this.getClass(ele);
      if (curValue.indexOf(value) > -1) {
        curValue = (" " + curValue + " ").replace(" " + value + " ", " ");
      }
      ele.setAttribute("class", curValue.trim());
    }
  }
  /**
   * 元素是否存在值为@{value}的class
   */
  hasClass(ele, value) {
    let has = false;
    if (value) {
      const curValue = this.getClass(ele);
      if (curValue.indexOf(value) > -1) {
        has = true;
      }
    }
    return has;
  }
  exchangeBtnStatus(ele, isOn) {
    if (!ele) { return; }
    const onClass = "onBtn", offClass = "offBtn";
    if (isOn) {
      this.removeClass(ele, offClass);
      this.addClass(ele, onClass);
    } else {
      this.removeClass(ele, onClass);
      this.addClass(ele, offClass);
    }
  }

  beforeChange(event) {
    if (this.videosData[this.index].substring(this.videosData[this.index].lastIndexOf('.')) === '.mp4') {
      this.videoPlayIcon = this.queryById('id-centerPlayIcon' + this.index);
      this.video[this.index].pause(); // 暂停上一个视频播放
      this.exchangeBtnStatus(this.videoPlayIcon, true); // 上一个视频显示播放按钮
    }

  }

  afterChange(event) {
    this.index = Number(event);
    this.getCurrentTitle();
    const self = this;
    if (this.tagData.videoUrl && this.videosData[this.index].substring(this.videosData[this.index].lastIndexOf('.')) === '.mp4') {

      setTimeout(() => {
        document.getElementById('footer-drag-progress').addEventListener("touchstart", () => {
          this.showDaggerProgress = true;
        });
        document.getElementById('footer-drag-progress').addEventListener("touchend", () => {
          setTimeout(() => {
            this.showDaggerProgress = false;
          }, 800);
          const currentValue = Number(this.range.value) ;
          this.video[this.index].currentTime = (this.video[this.index].duration * (currentValue / 100)).toFixed(2);
        });
      }, 1);

      this.test = true ;
      // video事件更新
      if (self.video && self.video[this.index]) {
        self.video[this.index].addEventListener("timeupdate", () => {
          if (this.index >= this.video.length) {
            return;
          } else {
            this.percent  = (100 / this.video[this.index].duration) * this.video[this.index].currentTime;
            const playProgressInner = document.getElementById('play-progress-inner');
            if (playProgressInner) {
              playProgressInner.setAttribute( 'style', 'width:' + this.percent + '%');
            }
            if (!this.showDaggerProgress && this.range !== undefined) {
              this.range.value = this.percent;
              // 更新当前时间
              this.currentTime = this.getTimeBySecond(this.video[this.index].currentTime);
              this.totalTime = this.getTimeBySecond(this.video[this.index].duration);
            }

          }

        });
      }
      const playBtn = document.getElementById('id-playBtn' + this.index);
      if (playBtn) {
        playBtn.click(); // 播放视频
      }
    } else {
      this.test = false ;
    }

  }

  // 退出当前弹窗
  cancel() {
    this.modalController.dismiss();
  }


  /**
   * 获取time格式字符串
   */
    getTimeBySecond(second: any) {
    // tslint:disable-next-line:radix
    const hour = parseInt((second / (60 * 60)).toFixed(0));
    // tslint:disable-next-line:radix
    const minute = parseInt(((second / 60) % 60).toFixed(0));
    // tslint:disable-next-line:radix
    const subSecond = parseInt((second % 60).toFixed(0));
    // tslint:disable-next-line:max-line-length
    return (hour > 0 ? ((hour < 10 ? "0" + hour : hour) + ":") : "") + (minute < 10 ? "0" + minute : minute) + ":" + (subSecond < 10 ? "0" + subSecond : subSecond);
  }

}
